import requests
import json
from datetime import datetime, timedelta
import calendar
from decimal import Decimal
from django.utils import timezone
from .models import TransactionRecord
from login.models import User
import logging

logger = logging.getLogger(__name__)

class DriverIncomeAnalyzer:
    """车主收入分析Agent"""
    
    def __init__(self):
        self.model_name = "qwen-plus-2025-07-14"
        self.api_key = "sk-3e3ce3cfc35545bf887db4caa4e396e4"
        self.api_url = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation"
    
    def get_driver_transactions(self, driver_id, start_date, end_date):
        """获取指定司机在日期范围内的交易记录"""
        try:
            driver = User.objects.get(id=driver_id)
            transactions = TransactionRecord.objects.filter(
                driver_id=driver,
                transaction_time__gte=start_date,
                transaction_time__lte=end_date,
                transaction_type=0  # 只统计收入
            ).order_by('transaction_time')
            
            return transactions
        except User.DoesNotExist:
            logger.error(f"司机不存在: {driver_id}")
            return None
    
    def calculate_income_metrics(self, transactions):
        """计算收入指标（包含日、周、月统计）"""
        if not transactions:
            return {}
        
        total_income = sum(t.amount for t in transactions)
        transaction_count = transactions.count()
        
        # 按天统计
        daily_stats = {}
        for t in transactions:
            date_key = t.transaction_time.date()
            if date_key not in daily_stats:
                daily_stats[date_key] = {
                    'income': Decimal('0'),
                    'count': 0
                }
            daily_stats[date_key]['income'] += t.amount
            daily_stats[date_key]['count'] += 1
        
        # 按周统计 - 修复：正确计算每周的天数和收入
        weekly_stats = {}
        week_days = {}  # 记录每周包含哪些天
        
        for t in transactions:
            date_obj = t.transaction_time.date()
            year, week_num, _ = date_obj.isocalendar()
            week_key = f"{year}-W{week_num:02d}"
            
            if week_key not in weekly_stats:
                weekly_stats[week_key] = {
                    'income': Decimal('0'),
                    'count': 0,
                    'days': set()  # 使用set去重
                }
            
            weekly_stats[week_key]['income'] += t.amount
            weekly_stats[week_key]['count'] += 1
            weekly_stats[week_key]['days'].add(date_obj)
        
        # 转换set为count并计算平均值
        for week_key in weekly_stats:
            week_data = weekly_stats[week_key]
            week_data['days'] = len(week_data['days'])  # 实际运营天数
            week_data['avg_daily_income'] = float(week_data['income'] / week_data['days']) if week_data['days'] > 0 else 0
            week_data['avg_order_income'] = float(week_data['income'] / week_data['count']) if week_data['count'] > 0 else 0
            week_data['income'] = float(week_data['income'])
        
        # 按月统计 - 修复：正确计算每月的天数和收入
        monthly_stats = {}
        month_days = {}  # 记录每月包含哪些天
        
        for t in transactions:
            date_obj = t.transaction_time.date()
            month_key = date_obj.strftime("%Y-%m")
            
            if month_key not in monthly_stats:
                monthly_stats[month_key] = {
                    'income': Decimal('0'),
                    'count': 0,
                    'days': set()  # 使用set去重
                }
            
            monthly_stats[month_key]['income'] += t.amount
            monthly_stats[month_key]['count'] += 1
            monthly_stats[month_key]['days'].add(date_obj)
        
        # 转换set为count并计算平均值
        for month_key in monthly_stats:
            month_data = monthly_stats[month_key]
            month_data['days'] = len(month_data['days'])  # 实际运营天数
            month_data['avg_daily_income'] = float(month_data['income'] / month_data['days']) if month_data['days'] > 0 else 0
            month_data['avg_order_income'] = float(month_data['income'] / month_data['count']) if month_data['count'] > 0 else 0
            month_data['income'] = float(month_data['income'])
        
        # 计算日均收入
        days_count = len(daily_stats)
        avg_daily_income = total_income / days_count if days_count > 0 else 0
        
        # 计算平均每单收入
        avg_order_income = total_income / transaction_count if transaction_count > 0 else 0
        
        # 找出收入最高和最低的日期
        max_income_date = max(daily_stats.items(), key=lambda x: x[1]['income']) if daily_stats else None
        min_income_date = min(daily_stats.items(), key=lambda x: x[1]['income']) if daily_stats else None
        
        # 找出收入最高和最低的周
        max_income_week = max(weekly_stats.items(), key=lambda x: x[1]['income']) if weekly_stats else None
        min_income_week = min(weekly_stats.items(), key=lambda x: x[1]['income']) if weekly_stats else None
        
        # 找出收入最高和最低的月
        max_income_month = max(monthly_stats.items(), key=lambda x: x[1]['income']) if monthly_stats else None
        min_income_month = min(monthly_stats.items(), key=lambda x: x[1]['income']) if monthly_stats else None
        
        return {
            'total_income': float(total_income),
            'transaction_count': transaction_count,
            'days_count': days_count,
            'avg_daily_income': float(avg_daily_income),
            'avg_order_income': float(avg_order_income),
            'max_income_date': str(max_income_date[0]) if max_income_date else None,
            'max_income_value': float(max_income_date[1]['income']) if max_income_date else 0,
            'min_income_date': str(min_income_date[0]) if min_income_date else None,
            'min_income_value': float(min_income_date[1]['income']) if min_income_date else 0,
            'max_income_week': max_income_week[0] if max_income_week else None,
            'max_income_week_value': max_income_week[1]['income'] if max_income_week else 0,
            'min_income_week': min_income_week[0] if min_income_week else 0,
            'min_income_week_value': min_income_week[1]['income'] if min_income_week else 0,
            'max_income_month': max_income_month[0] if max_income_month else None,
            'max_income_month_value': max_income_month[1]['income'] if max_income_month else 0,
            'min_income_month': min_income_month[0] if min_income_month else None,
            'min_income_month_value': min_income_month[1]['income'] if min_income_month else 0,
            'daily_stats': {str(k): {'income': float(v['income']), 'count': v['count']} for k, v in daily_stats.items()},
            'weekly_stats': weekly_stats,
            'monthly_stats': monthly_stats
        }
    
    def generate_analysis_report(self, driver_id, start_date, end_date, metrics):
        """使用大模型生成分析报告（包含周月数据）"""
        
        # 构建提示词
        prompt = f"""
        作为车主收入分析专家，请分析以下司机的收入数据：
        
        司机ID: {driver_id}
        分析时间段: {start_date} 至 {end_date}
        
        基础收入指标：
        - 总收入: ¥{metrics['total_income']:.2f}
        - 订单数量: {metrics['transaction_count']}单
        - 运营天数: {metrics['days_count']}天
        - 日均收入: ¥{metrics['avg_daily_income']:.2f}
        - 平均每单收入: ¥{metrics['avg_order_income']:.2f}
        
        收入分布：
        - 最高收入日期: {metrics['max_income_date']} (¥{metrics['max_income_value']:.2f})
        - 最低收入日期: {metrics['min_income_date']} (¥{metrics['min_income_value']:.2f})
        
        周度收入统计：
        - 最高收入周: {metrics['max_income_week']} (¥{metrics['max_income_week_value']:.2f})
        - 最低收入周: {metrics['min_income_week']} (¥{metrics['min_income_week_value']:.2f})
        
        月度收入统计：
        - 最高收入月: {metrics['max_income_month']} (¥{metrics['max_income_month_value']:.2f})
        - 最低收入月: {metrics['min_income_month']} (¥{metrics['min_income_month_value']:.2f})
        
        请提供：
        1. 收入表现分析（按日、周、月三个维度）
        2. 收入波动原因分析
        3. 具体的收入优化建议（至少5条）
        4. 未来7天的收入预测和建议
        5. 周度和月度收入趋势分析
        
        请以JSON格式返回，包含以下字段：
        - "analysis_summary": 收入表现总结
        - "performance_evaluation": 表现评价
        - "optimization_suggestions": 优化建议数组
        - "weekly_forecast": 下周预测
        - "risk_warnings": 风险提醒
        - "trend_analysis": 趋势分析
        """
        
        try:
            headers = {
                'Authorization': f'Bearer {self.api_key}',
                'Content-Type': 'application/json'
            }
            
            data = {
                "model": self.model_name,
                "input": {
                    "messages": [
                        {
                            "role": "user",
                            "content": prompt
                        }
                    ]
                },
                "parameters": {
                    "result_format": "message",
                    "max_tokens": 2500,
                    "temperature": 0.7
                }
            }
            
            response = requests.post(self.api_url, headers=headers, json=data)
            response.raise_for_status()
            
            result = response.json()
            content = result['output']['choices'][0]['message']['content']
            
            # 解析JSON响应
            try:
                analysis_result = json.loads(content)
            except json.JSONDecodeError:
                # 如果返回的不是JSON，构建结构化响应
                analysis_result = {
                    "analysis_summary": content,
                    "performance_evaluation": "需要进一步分析",
                    "optimization_suggestions": [
                        "建议增加高峰时段出车频率",
                        "关注订单密集区域提高接单效率",
                        "合理规划休息时间避免疲劳驾驶",
                        "关注平台奖励活动提高额外收入",
                        "保持车辆良好状态提升乘客满意度"
                    ],
                    "weekly_forecast": "预计下周收入将保持稳定",
                    "risk_warnings": ["注意避免疲劳驾驶"],
                    "trend_analysis": "收入趋势需要更多数据支持"
                }
            
            return analysis_result
            
        except Exception as e:
            logger.error(f"大模型分析失败: {str(e)}")
            # 返回默认分析结果
            return {
                "analysis_summary": f"司机{driver_id}在{start_date}至{end_date}期间总收入¥{metrics['total_income']:.2f}，日均收入¥{metrics['avg_daily_income']:.2f}。",
                "performance_evaluation": "收入表现中等",
                "optimization_suggestions": [
                    "建议在工作 evenings 晚上6-9点增加出车时间",
                    "周末可选择在商业区、景区等人流密集区域接单",
                    "关注平台早晚高峰奖励政策",
                    "保持车辆整洁提高乘客评价",
                    "合理规划路线减少空驶率"
                ],
                "weekly_forecast": "根据历史数据，预计下周日均收入在¥{metrics['avg_daily_income'] * 0.9:.2f}-¥{metrics['avg_daily_income'] * 1.1:.2f}之间",
                "risk_warnings": ["注意劳逸结合，避免疲劳驾驶"],
                "trend_analysis": "建议持续关注周度和月度收入变化趋势"
            }
    
    def analyze_driver_income(self, driver_id, start_date, end_date):
        """完整的司机收入分析流程"""
        
        # 转换日期格式并处理时区
        from django.utils.timezone import make_aware
        from datetime import datetime, time
        
        start_dt = make_aware(datetime.strptime(start_date, '%Y-%m-%d'))
        # 结束日期设置为当天的23:59:59
        end_dt = make_aware(datetime.strptime(end_date, '%Y-%m-%d') + timedelta(days=1) - timedelta(seconds=1))
        
        # 获取交易数据
        transactions = self.get_driver_transactions(driver_id, start_dt, end_dt)
        if transactions is None:
            return {"error": "司机不存在或查询失败"}
        
        if not transactions:
            return {
                "driver_id": driver_id,
                "start_date": start_date,
                "end_date": end_date,
                "metrics": {},
                "analysis": {
                    "analysis_summary": "该时间段内无收入记录",
                    "performance_evaluation": "无数据",
                    "optimization_suggestions": ["建议开始接单以获取收入数据"],
                    "weekly_forecast": "开始接单后将生成详细分析",
                    "risk_warnings": [],
                    "trend_analysis": "暂无趋势数据"
                }
            }
        
        # 计算指标
        metrics = self.calculate_income_metrics(transactions)
        
        # 生成分析报告
        analysis = self.generate_analysis_report(driver_id, start_date, end_date, metrics)
        
        return {
            "driver_id": driver_id,
            "start_date": start_date,
            "end_date": end_date,
            "metrics": metrics,
            "analysis": analysis
        }